<template>
  <el-dialog title="权限分配" :close-on-click-modal="false" :show-close="false"
             :visible.sync="permShow" width="40%" @open="handleShow">

    <el-form>
      <el-form-item>
        <el-select v-model="selectedMid" placeholder="请选择权限">
          <el-option v-for="item in noMenus" :key="item.id" :label="item.label" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addPerm">添加</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="hasMenus" style="width: 100%" border
              :header-cell-style="{ 'text-align': 'center' }"
              :cell-style="{ 'text-align': 'center' }">
      <el-table-column label="已分配的角色">
        <el-table-column prop="id" label="#ID"></el-table-column>
        <el-table-column prop="label" label="标签"></el-table-column>
        <el-table-column prop="perms" label="权限"></el-table-column>
        <el-table-column label="操作" width="60px">
          <template slot-scope="scope">
            <el-button type="danger" icon="el-icon-delete" size="small"
                       @click="delPermission(scope.row.id)" circle>
            </el-button>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>

  </el-dialog>
</template>

<script>
import {roleNoPerm, getMenusByRole, delMenuByRole} from "@/api/menu";
import {assign} from "@/api/systrm-role";

export default {
  data() {
    return {
      noMenus: [],
      hasMenus: [],
      selectedMid: ''
    }
  },
  methods: {
    closeDialog() {
      this.$emit('closeDialog')
    },
    addPerm() {
      const roleMenu = {
        roleId: this.id,
        menuId: this.selectedMid
      }
      assign(roleMenu).then(res => {
        this.$message.success('权限分配成功')
        this.selectedMid = ''
        this.getNotMenus()
        this.getHasMenus()
      }).catch(err => {
        this.$message.error('权限分配失败')
      })
    },
    getHasMenus() {
      getMenusByRole(this.id).then(res => {
        this.hasMenus = res
      }).catch(err => {
        this.$message.error('获取权限列表失败')
      })
    },
    getNotMenus() {
      roleNoPerm(this.id).then(res => {
        this.noMenus = res
      }).catch(err => {
        this.$message.error('获取权限列表失败')
      })
    },
    delPermission(mid) {
      const roleMenu = {
        roleId: this.id,
        menuId: mid
      }
      delMenuByRole(roleMenu).then(res => {
        this.$message.success('删除成功')
        this.getNotMenus()
        this.getHasMenus()
      }).catch(err => {

      })
    },
    handleShow() {
      this.getNotMenus()
      this.getHasMenus()
    }
  },
  props: {
    permShow: {
      type: Boolean,
      default: false
    },
    id: {
      type: Number | String,
      default: 0
    }
  }
}
</script>

<style scoped>

</style>
